﻿namespace MicroCloud.CodeGeneration.Database
{
    //[Dependency(ServiceLifetime.Singleton, TryAdd = true)]
    public class CodeProjectSeedDataInitializer : SeedDataInitializerBase<CodeProject, Guid>
    {
        /// <summary>
        /// 初始化一个<see cref="T:MicroCloud.Entity.SeedDataInitializerBase`2" />类型的新实例
        /// </summary>
        public CodeProjectSeedDataInitializer(IServiceProvider rootProvider)
            : base(rootProvider)
        { }

        /// <summary>获取 种子数据初始化的顺序</summary>
        public override decimal OrderNo => 1;

        /// <summary>是否强制执行</summary>
        public override bool ForceSync => true;

        /// <summary>重写以提供要初始化的种子数据</summary>
        /// <returns></returns>
        protected override CodeProject[] SeedData(IServiceProvider provider)
        {
            return [];
        }

        /// <summary>重写以提供判断某个实体是否存在的表达式</summary>
        /// <param name="entity">要判断的实体</param>
        /// <returns></returns>
        protected override Expression<Func<CodeProject, bool>> ExistingExpression(CodeProject entity)
        {
            return m => m.Name == entity.Name;
        }

        /// <summary>将种子数据初始化到数据库</summary>
        protected override void SyncToDatabase(CodeProject[] entities, IServiceProvider provider)
        {
            if (entities == null || entities.Length == 0) return;

            IDataContract contract = provider.GetRequiredService<IDataContract>();
            var dtos = entities.Select(m => new CodeProjectInDto()
            {
                Id = m.Id,
                Name = m.Name,
                NamespacePrefix = m.NamespacePrefix,
                Company = m.Company,
                Creator = m.Creator,
                Copyright = m.Copyright,
                RootPath = m.RootPath,
            }).ToArray();
            contract.CreateCodeProjects(dtos);
        }
    }
}